#include <stdio.h>
#include <string.h>
#include <iconv.h>
#include "url.h"
#include "aes.h"

//static int utf8_to_gb(char *out, size_t size, const char *str)
int utf8_to_gb(char *out, size_t size, const char *str)
{
    iconv_t handle;
    size_t len;
    size_t left;
    
    char *ptr, *result;

    len = strlen(str);
    handle = iconv_open("gb18030", "utf-8");
    if(handle == 0)
        return -1;

    ptr = (char *)str;
    result = out;
    memset(result, 0, size);
    left = size;
    if (iconv(handle, &ptr, &len, &result, &left) == -1)
        return -1;
    iconv_close(handle);

    return (result - out);
}

//static int encode_hex(char *dst, const char *src, size_t len)
int encode_hex(char *dst, const char *src, size_t len)
{
    const static unsigned char hex_char[] = "0123456789abcdef";
    int i;

    for (i = 0;i < len;i ++) {
	unsigned char ch;
	ch = (unsigned char) src[i];

	dst[2 * i] = hex_char[(ch >> 0x04)];
	dst[2 * i + 1] = hex_char[ch & 0x0F];
    }

    dst[2 * len] = 0;
    return 2 * len;
}

int pps2tvod(char *out, size_t size, const char *url, int id)
{
    int  len;
    char *ptr;
    char plain[1024];
    char cipher[1024];
    int i;
    const static unsigned char key[16] = "884d977e1a515ae4";

    AES_KEY aes_key;

    if (out == NULL || url == NULL)
	return -1;

    if (strncmp(url, "pps://", 6) != 0)
	return -1;

    url += 6;
    ptr = strchr(url, '/');
    if (ptr == NULL)
	return -1;

    len = ptr - url;

    if (size < (2 * len + 0x20)) {
	fprintf(stderr, "buffer to small!\n");
	return -1;
    }

    memcpy(plain, url, len);
    snprintf(&plain[len], 1023, "00000000/%d", id);

    /* padding */
    len = strlen(plain);

    for (i = 0;i < 0x10;i ++)
	plain[len + i] = '\0';

    if (len % 16) {
	len = len + 16 - len % 16;
    } 

    AES_set_encrypt_key((const unsigned char *)&key, 128, &aes_key);

    for (i=0;i< len / 16;i ++) {
	AES_encrypt((const unsigned char *)&plain[i * 16], (unsigned char *)&cipher[i * 16],&aes_key);
    }

    strncpy(out, "tvod://", 7);
    out += 7;

    encode_hex(out, cipher, len);

    strcat(out, ptr);

    return 0;
}

/*
int main(int argc, char *argv[])
{
    int len;
    char *url, *ptr;
    char gb_url[1024];
    char tvod_url[1024];

    if (argc != 2)
	return -1;

    url_unescape(argv[1]);
    url = argv[1];

    if (strncmp(url, "pps://", 6) != 0)
	return -1;
    url += 6;

    len = utf8_to_gb(gb_url, 1024, url);
    if (len < 0)
	return -1;

    ptr = url_escape(gb_url);
    if (ptr == NULL)
	return -1;

    strcpy(url, ptr);
    pps2tvod(tvod_url, 1023, argv[1], 0);
    printf("%s\n", tvod_url);
    return 0;
}
*/
